package com.jlju.djmhadmin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlju.djmhadmin.common.GenericResponse;
import com.jlju.djmhadmin.common.util.JsonUtil;
import com.jlju.djmhadmin.common.util.RequiredStringValidator;
import com.jlju.djmhadmin.common.util.StringUtils;
import com.jlju.djmhadmin.common.util.Validations;
import com.jlju.djmhadmin.dao.common.util.MailUtil;
import com.jlju.djmhadmin.dao.entity.Stuents;
import com.jlju.djmhadmin.dao.entity.Student;
import com.jlju.djmhadmin.dao.service.StudentService;
import com.jlju.djmhadmin.dao.service.StuentsService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * All rights Reserved, Designed By Liting.
 *
 * @description: 学生请假相关controller
 * @author: LiTing[liting08011@163.com]
 * @create: 2018-04-19 17:51
 * @Copyright ©2018 Liting. All rights reserved.
 * 注意：本内容仅限于吉林建筑大学ACM协会内部传阅，禁止外泄以及用于其他的商业用途。
 **/
@RestController
@Slf4j
@RequestMapping("/stuents")
public class StuentsController {
    
    private Logger logger = LoggerFactory.getLogger(this.getClass());

//    @Autowired
//    private MailUtil mailUtil;

    @Autowired
    private StuentsService stuentsService;

    @Autowired
    private StudentService studentService;

    @ApiOperation("新增请假信息")
    @RequestMapping(value = "/add")
    @Validations(requiredStrings={
            @RequiredStringValidator(fieldName="name",errCode="ACM0204",errMsg="请求参数不足,姓名不能为空"),
            @RequiredStringValidator(fieldName="className",errCode="ACM0206",errMsg="请求参数不足，班级不能为空"),
            @RequiredStringValidator(fieldName="acNo",errCode="ACM0207",errMsg="请求参数不足，学号不能为空"),
            @RequiredStringValidator(fieldName="cause",errCode="ACM0302",errMsg="请求参数不足，假由不能为空"),
            @RequiredStringValidator(fieldName="days",errCode="ACM0303",errMsg="请求参数不足，请假天数不能为空")
    })
    public Callable<GenericResponse<String>> add(@RequestBody String json) {
        logger.info("***新增请假信息添加开始*** 入参： " + json);
        try {
            Stuents stuents = JsonUtil.jsonToObject(json,Stuents.class);
            //验证学生信息
            Student student = new Student(stuents.getName(), stuents.getAcNo());
            student = this.studentService.getByAcNo(student);
            if(StringUtils.isEmpty(student)) {
                throw new Exception("学生信息不吻合！");
            }
            stuents.setClassName(student.getClassName());
            this.stuentsService.add(stuents);
            logger.info("***请假信息添加成功***" + stuents);
            try{
                MailUtil mailUtil = new MailUtil();
//                mailUtil.postMail("liting08011@163.com", "aaaaaaa");
                mailUtil.postMail("liting08011@163.com","请假信息：姓名 ：" + stuents.getName() + "班级 ： " + stuents.getClassName() + "假由：" + stuents.getCause() + "请假天数 ： " + stuents.getDays());
            } catch (Exception e) {
                logger.error("邮件发送失败 " + e);
            }
            return () -> GenericResponse.success("ACM0008", "添加成功", stuents);
        } catch (Exception e) {
            logger.error("***请假信息添加失败***" + e);
            return () -> GenericResponse.failed("ACM9999", e.toString());
        }
    }

    @RequiredStringValidator(fieldName="uuid",trim=true,errCode="ACM0304",errMsg="请求参数不足,请假单号不能为空")
    @ApiOperation("删除请假信息")
    @RequestMapping(value = "/delete")
    public Callable<GenericResponse<String>> delete(@RequestBody String json) {
        logger.info("***请假信息删除开始***");
        try {
            json = StringUtils.trimFirstAndLastChar(json,'\"');
            Stuents stuents = new Stuents(json);
            this.stuentsService.deleteById(stuents);
            logger.info("***请假信息删除成功***");
            return () -> GenericResponse.success("ACM0100", "销假成功", stuents);
        } catch (Exception e) {
            logger.error("***请假信息删除失败***" + e);
            return () -> GenericResponse.failed("ACM0101", "销假失败");
        }
    }

    @RequiredStringValidator(fieldName="uuid",trim=true,errCode="ACM0304",errMsg="请求参数不足,请假单号不能为空")
    @ApiOperation("更新请假信息-审批通过")
    @RequestMapping(value = "/updateNext")
    public Callable<GenericResponse<String>> updateNext(@RequestBody String json) {
        logger.info("***请假信息更新开始***入参：" + json);
        try {
            json = StringUtils.trimFirstAndLastChar(json,'\"');
            Stuents stuents = new Stuents(json);
            stuents.setStatus("1");
            this.stuentsService.updateById(stuents);
            logger.info("***请假信息更新成功***");
//            try {
//                MailUtil mailUtil = new MailUtil();
//                mailUtil.postMail(finalStudent.getEmail(), "新生注册成功---学号--" + finalStudent.getAcNo() + "姓名" + finalStudent.getName() + "班级" + finalStudent.getClassName() + "请于指定报道时间到校报道");
//            } catch (Exception e) {
//                logger.error("***新生注册成功，未发送邮件***");
//            }
            return () -> GenericResponse.success("ACM0014", "更新成功", stuents);
        } catch (Exception e) {
            logger.error("***请假信息更新失败***" + e);
            return () -> GenericResponse.failed("ACM0015", "更新失败");
        }
    }

    @RequiredStringValidator(fieldName="uuid",trim=true,errCode="ACM0304",errMsg="请求参数不足,请假单号不能为空")
    @ApiOperation("更新请假信息-拒绝审批")
    @RequestMapping(value = "/updateRef")
    public Callable<GenericResponse<String>> updateRef(@RequestBody String json) {
        logger.info("***请假信息更新开始***入参：" + json);
        try {
            json = StringUtils.trimFirstAndLastChar(json,'\"');
            Stuents stuents = new Stuents(json);
            stuents.setStatus("2");
            this.stuentsService.updateById(stuents);
            logger.info("***请假信息更新成功***");
            return () -> GenericResponse.success("ACM0014", "更新成功", stuents);
        } catch (Exception e) {
            logger.error("***请假信息更新失败***" + e);
            return () -> GenericResponse.failed("ACM0015", "更新失败");
        }
    }

    @ApiOperation("查看全部请假信息，带分页")
    @RequestMapping(value = "/findAll")
    public Callable<GenericResponse<List<Stuents>>> findAll(@RequestBody String json, int pageNum, int pageSize) {
        logger.info("***查看全部请假信息信息（分页）***");
        try {
            Stuents stuents = JsonUtil.jsonToObject(json,Stuents.class);
            PageHelper.startPage(pageNum, pageSize);
            List<Stuents> list = this.stuentsService.findAll(stuents);
            // 用PageInfo对结果进行包装
            PageInfo<Stuents> pageInfo = new PageInfo<Stuents>(list);
            logger.info("***查看全部请假信息信息（分页） 成功***");
            return () -> GenericResponse.success("ACM0010", "查询成功", pageInfo);
        } catch (Exception e) {
            logger.error("***查看全部请假信息信息（分页）失败***" + e);
            return () -> GenericResponse.failed("ACM0011", "查询失败");
        }
    }

    @ApiOperation("查看详细请假信息信息")
    @RequestMapping(value = "/findOneById")
    public Callable<GenericResponse<String>> findOneById(@RequestBody String json) {
        logger.info("***请假信息信息查询开始***");
        try {
            Stuents stuents = JsonUtil.jsonToObject(json,Stuents.class);
            Stuents finalStuents = this.stuentsService.findOneById(stuents.getAcNo());
            logger.info("***请假信息信息查询成功***");
            return () -> GenericResponse.success("ACM0012", "详细查询成功", finalStuents);
        } catch (Exception e) {
            logger.error("***请假信息信息查询失败***" + e);
            return () -> GenericResponse.failed("ACM0013", "查询详情失败");
        }
    }
}